package com.example.micrauth.contorller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.example.micrapi.feign.SysMenuServiceFeign;
import com.example.micrapi.pojo.SysMenu;
import com.example.micrapi.pojo.SysRole;
import com.example.micrauth.domain.vo.LoginUserVO;
import com.example.micrauth.domain.vo.RouterVO;
import com.example.micrauth.domain.vo.RespResult;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @description: 获取Menus权限列表
 * @author: uu
 * @date: 2024/3/3 19:14
 * @version: 1.0
 */
@Tag(name="用户菜单")
@RestController
@RequestMapping("/sys")
public class SysMenuController {
    @Autowired
    private SysMenuServiceFeign sysMenuServiceFeign;

    @Operation(summary = "查看用户的菜单", description = "根据用户的角色id查询菜权限")
    @GetMapping("/menus")
    public RespResult getSysMenus() {
        LoginUserVO loginUserVO = (LoginUserVO) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        List<SysRole> roleList = loginUserVO.getSysUser().getRoleList();
        List<Integer> roleIds = roleList.stream().map(sysRole -> sysRole.getId()).collect(Collectors.toList());
        List<SysMenu> sysMenus = sysMenuServiceFeign.findByRoleIds(roleIds);
        // 设计树形结构
        List<RouterVO> router = getRouter(sysMenus);
        return RespResult.success().Data(router);
    }


    private List<RouterVO> getRouter(List<SysMenu> sysMenus) {
        List<RouterVO> routerVOS = new ArrayList<>();

        List<SysMenu> parentSySMenus = sysMenus.stream().filter(sysMenu -> sysMenu.getPid() == 0).collect(Collectors.toList());
        parentSySMenus.forEach(parentSySMenu -> {
            RouterVO routerVO = new RouterVO();
            BeanUtil.copyProperties(parentSySMenu, routerVO);
            routerVOS.add(routerVO);
        });
        setChildRouterVO(routerVOS, sysMenus);
        return routerVOS;
    }

    private void setChildRouterVO(List<RouterVO> parentRouterVOs, List<SysMenu> sysMenus) {
        if (ObjectUtil.isNull(parentRouterVOs))
            return;
        parentRouterVOs.forEach(routerVO -> {
            List<RouterVO> childRouterVOs = sysMenus.stream().filter(sysMenu -> sysMenu.getPid() == routerVO.getId()).map(sysMenu -> {
                RouterVO router = new RouterVO();
                BeanUtil.copyProperties(sysMenu, router);
                return router;
            }).collect(Collectors.toList());
            routerVO.setChildren(childRouterVOs);
            setChildRouterVO(childRouterVOs, sysMenus);
        });
    }

}
